﻿using DiLe.Mes.Application.Common.Equipment;
using DiLe.Mes.Application.Local;
using DiLe.Mes.Model.Cloud.Dashboard.Statistics;
using DiLe.Mes.Model.Common.Abnormal.Entity;
using DiLe.Mes.Model.Local.Abnormal.Entity;
using EasyNetQ;
using MapleLeaf.Core.Entity;
using MapleLeaf.Core.EventBus;
using Quartz;

namespace DiLe.Mes.Local.Jobs {
    /// <summary>
    /// 
    /// </summary>
    [DisallowConcurrentExecution]
    public class DataPushAlarmJob : IJob {


        private readonly static AbnormalClient _abnormalClient = AppHelper.GetService<AbnormalClient>();
        private readonly static EquipmentManageClient _equipmentManage = AppHelper.GetService<EquipmentManageClient>();
        private readonly static IBus _ibus = AppHelper.GetService<IBus>();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context) {
            await PushAlarmInfo();
        }

        /// <summary>
        /// 
        /// </summary>
        public static async Task PushAlarmInfo() {
            var pushDatas = await _abnormalClient.GetAlarmInfoListAsync(p => p.IsPushed == false);
            pushDatas = pushDatas?.Where(x => !x.AlarmData.IsNullOrEmpty()).ToList();
            if (pushDatas == null || pushDatas.None()) {
                return;
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "AlarmInfo"
            };
            _ibus.SendReceive.Send("data_push_alarm", model);
            var datas = pushDatas.Where(x => x.IsAlarmRelease == true && x.EndAlarmTime != null).ToList();
            foreach (var item in datas) {
                item.IsPushed = true;
            }
            await _abnormalClient.UpdateAlarmInfoAsync(datas);
        }
    }
}
